import React, { Component } from 'react'
import {Input, Radio, Upload, Dialog, Message, Button} from 'element-react'
import DatePicker from '../../base/DatePicker'
import {withRouter} from 'react-router-dom'
import Breadcrumb from '../../base/Breadcrumb'
import Quill from 'quill'
import 'quill/dist/quill.snow.css'

class skuOperate extends Component {
  constructor (props) {
    super(props)
    this.state = {
      id: this.props.match.params.id,
      // 上传图片参数
      dialogImageUrl: '',
      repertory: '',
      unit: '',
      imgs: [],
      name: sessionStorage.skuName,
      dialogVisible: false,
      // 产品描述
      value: '',
      // 状态
      status: null
    }
    this.editor = null
  }
  componentDidMount () {
    const textbox = this.refs.textarea
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
      ['blockquote', 'code-block'],
      [{ 'header': 1 }, { 'header': 2 }],               // custom button values
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
      [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
      [{ 'direction': 'rtl' }],
      [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
      [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
      [{ 'font': [] }],
      [{ 'align': [] }],
      ['image', 'video'],
      ['clean']                                         // remove formatting button
    ]
    const options = {
      debug: 'warn',
      modules: {
        toolbar: toolbarOptions
      },
      placeholder: '请输入文本...',
      readOnly: false,
      theme: 'snow'
    }
    let editor =this.editor= new Quill(textbox,options)
    let {value}=this.state
    if (value) editor.clipboard.dangerouslyPasteHTML(value)
    editor.on('text-change', this.handleChange.bind(this))
    this.init()
  }
  // 获取sku详情，初始化
  init () {
    this.$ajax.getSkuDetail(this.state.id).then(res => {
      if (res.code === 200) {
        let {repertory, status, unit, startTime, endTime, descrption, imgs} = res.data
        let value = descrption
        this.setState({repertory, status, unit, startTime, endTime, value, imgs})
      }
    }).catch(() => {
      Message.error('网络错误')
    })
  }
  handleChange () {
    let {value} = this.state
    value = this.editor.root.innerHTML
    this.setState({value},()=> {console.log(this.state.value)})
  }
  handleSuccess (response, file, fileList) {
    // console.log(response.data)
    console.log(file)
    let imgs = this.state.imgs
    imgs.push({
      name: file.name,
      url: response.data
    })
    // console.log(fileList)
  }
  handleError (err, file, fileList) {}
  // 设置时间
  getTime (startTime, endTime) {
    this.setState({startTime, endTime}, () => {console.log(this.state.startTime)})
  }
  statusFun (status) {
    this.setState({status: Number(status)})
  }
  submit () {
    let {repertory, status, unit, startTime, endTime, value, id, imgs, postfAdvertise, preAdvertise} = this.state
    console.log({repertory, status, unit, startTime, endTime, value, id, imgs, postfAdvertise, preAdvertise})
    this.$ajax.editSkuDetail({repertory, status, unit, startTime, endTime, description: value, id, imgs, postfAdvertise, preAdvertise}).then(res => {
      if (res.code === 200) {
        Message({
          message: '修改成功',
          type: 'success'
        })
      } else {
        Message('修改失败')
      }
    })
  }
  cancel () {
    this.props.history.goBack()
  }
  setRepertory (repertory) {
    if ((/\D/g).test(repertory)) {
      Message.error('请输入数字')
      return
    }
    this.setState({
      repertory: Number(repertory)
    })
  }
  render () {
    return (
      <div className="sku-operate">
        <Breadcrumb data={['商品管理', '商品规格', 'sku生成页', '编辑']}/>
        <div className="height40"></div>
        {/* sku名称： */}
        <div className="inputGroup">
          <label className="inputLabel">sku名称：</label>
          <Input placeholder="请输入产品名称" size="small" className="inputSmall" value={this.state.name} />
        </div>
        {/* sku卖点： */}
        <div className="inputGroup">
          <label className="inputLabel">sku卖点：</label>
          <div className="inline-marginR-20"><Input placeholder="前置广告" size="small" className="inputSmall" value={this.state.preAdvertise} onChange={preAdvertise => {this.setState({preAdvertise})}}/></div>
          <Input placeholder="后置广告" size="small" className="inputSmall" value={this.state.postfAdvertise} onChange={postfAdvertise => {this.setState({postfAdvertise})}}/>
        </div>
        {/* sku库存量： */}
        <div className="inputGroup">
          <label className="inputLabel">sku库存量：</label>
          <Input placeholder="" size="small" className="inputSmall" value={this.state.repertory} onChange={this.setRepertory.bind(this)}/>
        </div>
        {/* sku单位： */}
        <div className="inputGroup">
          <label className="inputLabel">sku单位：</label>
          <Input placeholder="" size="small" className="inputSmall" value={this.state.unit} onChange={unit => {this.setState({unit})}}/>
        </div>
        {/*缩略图*/}
        <div className="inputGroup">
          <label className="inputLabel">商品缩略图：</label>
          <div className="inline-marginR-20">
            <Upload
              action="http://tft-dev/api3/upload/file"
              listType="picture-card"
              fileList={this.state.imgs}
              onSuccess={(response, file, fileList) => this.handleSuccess(response, file, fileList)}
              onError={(err, file, fileList) => this.handleError(err, file, fileList)}
            >
              <i className="el-icon-plus"></i>
            </Upload>
            <Dialog
              visible={this.state.dialogVisible}
              size="tiny"
              onCancel={() => this.setState({ dialogVisible: false })}
            >
              <img width="100%" src={this.state.dialogImageUrl} alt="" />
            </Dialog>
          </div>
        </div>
        {/*产品描述*/}
        <div className="inputGroup">
          <label className="inputLabel">商品描述：</label>
          <div className="quill">
            <div ref="textarea"></div>
          </div>
        </div>
        <div className="inputGroup">
          <label className="inputLabel">有效期：</label>
          <DatePicker getTime={this.getTime.bind(this)}
                      setValue={true}
                      startTime={this.state.startTime}
                      endTime={this.state.endTime}/>
        </div>
        {/* 状态 */}
        <div className="inputGroup">
          <label className="inputLabel">状态：</label>
          <Radio.Group value={this.state.status} onChange={this.statusFun.bind(this)}>
            <Radio value="1">已上架</Radio>
            <Radio value="0">未上架</Radio>
          </Radio.Group>
        </div>
        <div className="height30"></div>
        <div className="btn-group discount-btn-group">
          <Button type="success" size="large" onClick={this.submit.bind(this)}>提交</Button>
          <Button type="warning" size="large" onClick={this.cancel.bind(this)}>取消</Button>
        </div>
      </div>
    )
  }
}

export default withRouter(skuOperate)